package com.rudolfheszele.smsselector.controller;

import java.util.Iterator;
import java.util.LinkedList;

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;

import com.rudolfheszele.smsselector.controller.SmsReaderController.ProgressState;
import com.rudolfheszele.smsselector.model.SmsSelectorRuleSet;
import com.rudolfheszele.smsselector.model.SmsSelectorRuleSetEvaluationEngine;
import com.rudolfheszele.smsselector.model.SmsSelectorSmsMessage;


public class SmsSelectorSmsReaderThread extends Thread
{
	public SmsSelectorSmsReaderThread(SmsReaderController smsReaderController)
	{
		mMainController = (SmsSelectorMainController)ControllerFactoryFactory.getControllerFactory().getController();
		mSmsReaderController = smsReaderController;
		mPaused = false;
		mStopped = false;
	}
	
	@Override
	public void run()
	{
		Uri smsContentUri = Uri.parse("content://sms");
		Uri smsFolderUri = null;
		String sortOrder = "date DESC";
        Cursor cursor = null; 
        LinkedList<SmsSelectorRuleSet> ruleSets = mMainController.getRuleSets();
        String[] folders = new String[] {"inbox", "sent", "draft"};
        Activity activity = (Activity)mSmsReaderController.getView(0);
        
        mSmsReaderController.reportProgress(ProgressState.READING_STARTED_STATE, null);
        for(int i = 0; i < folders.length; i++)
        {
            int counter = 0;
            float percent = 0;
            SmsSelectorSmsMessage smsMessages[] = null;
            
            mSmsReaderController.reportProgress(ProgressState.DIRECTORY_CHANGED_STATE, folders[i]);
	        do
	        {
	        	smsFolderUri = Uri.withAppendedPath(smsContentUri, folders[i]);
	        	cursor = activity.getContentResolver().query(smsFolderUri, null, null, null, sortOrder);
		        if(cursor == null)
		        	break;
		        // Read the messages and apply the rules on them
		        try
		        {
			        cursor.moveToFirst();
			        smsMessages = new SmsSelectorSmsMessage[cursor.getCount()];
			        for(int j = 0; j < cursor.getCount(); j++)
			        {
			        	Iterator<SmsSelectorRuleSet> ruleSetIterator = ruleSets.iterator();
			        	
			        	smsMessages[j] = SmsSelectorSmsMessage.fetchMessageFromCursor(cursor, folders[i]);
			        	while(ruleSetIterator.hasNext())
			        	{
			        		SmsSelectorRuleSet ruleSet = ruleSetIterator.next();
			        		if(SmsSelectorRuleSetEvaluationEngine.isRuleSetMatch(ruleSet, smsMessages[j]) == true)
			        		{
			        			ruleSet.getAction().doAction(smsMessages[j]);
			        			break;
			        		}
			        	}
			        	counter++;
			        	percent = (float)counter / (float)cursor.getCount();
			        	percent *= 100;
			        	mSmsReaderController.reportProgress(ProgressState.NEW_PROGRESS_STATE, new Integer((int)percent));
			        	synchronized(this)
						{
							while(mPaused == true)
				        		wait();
							if(mStopped)
								return;
						}
			        	cursor.moveToNext();
			        }
		        }
		        catch(InterruptedException e)
	        	{
					e.printStackTrace();
				}
		        finally
		        {
		        	cursor.close();
		        }
	        }
	        while(false);
	        mMainController.addSmsMessages(smsMessages);
        }
        mSmsReaderController.reportProgress(ProgressState.READING_FINISHED_STATE, null);
        mSmsReaderController.smsReadingFinished();
	}
	
	public synchronized void pauseSmsReading()
	{
		mPaused = true;
	}
	
	public synchronized boolean isPaused()
	{
		return mPaused;
	}
	
	public synchronized void resumeSmsReading()
	{
		mPaused = false;
		notify();
	}
	
	public synchronized void stopSmsReading()
	{
		mStopped = true;
	}
	
	private SmsSelectorMainController mMainController;
	private SmsReaderController mSmsReaderController;
	private boolean mPaused;
	private boolean mStopped;
}
